package com.fragment4.service;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.template.IProvider;
import com.common.service.IUserService;

@Route(path = "/service/user")
public class UserServiceImpl implements IUserService, IProvider {

    private static final String PREF_NAME = "user_prefs";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ID = "user_id";

    // 使用静态变量确保全局唯一
    private static UserServiceImpl instance;
    private boolean isLoggedIn = false;
    private String username;
    private String userId;
    private SharedPreferences sharedPreferences;
    private Context context;

    // 私有构造函数
    private UserServiceImpl() {
    }

    // 提供获取实例的方法
    public static UserServiceImpl getInstance() {
        if (instance == null) {
            synchronized (UserServiceImpl.class) {
                if (instance == null) {
                    instance = new UserServiceImpl();
                }
            }
        }
        return instance;
    }

    @Override
    public boolean isLogin() {
        return isLoggedIn;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public String getUserId() {
        return userId;
    }

    @Override
    public void login(String username, String password, LoginCallback callback) {

        // 这里模拟登录过程
        new Thread(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(1000);

                // 模拟登录验证逻辑
                boolean loginSuccess = validateLogin(username, password);

                if (loginSuccess) {
                    // 登录成功
                    this.isLoggedIn = true;
                    this.username = username;
                    this.userId = "user_" + System.currentTimeMillis();

                    // 保存到 SharedPreferences
                    saveLoginState();

                    Log.d("UserServiceImpl", "登录成功: " + username);

                    // 回调成功
                    if (callback != null) {
                        callback.onSuccess(this.username, this.userId);
                    }
                } else {
                    // 登录失败
                    String errorMsg = "用户名或密码错误";
                    Log.w("UserServiceImpl", errorMsg);

                    // 回调失败
                    if (callback != null) {
                        callback.onFailure(errorMsg);
                    }
                }
            } catch (Exception e) {
                Log.e("UserServiceImpl", "登录异常", e);

                // 回调错误
                if (callback != null) {
                    callback.onError(e);
                }
            }
        }).start();

    }
    /**
     * 验证登录（模拟逻辑）
     */
    private boolean validateLogin(String username, String password) {
        // 在实际项目中，这里应该调用API验证
        // 这里简单模拟：用户名和密码都不为空就认为成功
        return username != null && !username.trim().isEmpty() &&
                password != null && !password.trim().isEmpty();

        // 或者模拟特定账号
        // return "admin".equals(username) && "123456".equals(password);
    }

    @Override
    public void logout() {
        this.isLoggedIn = false;
        this.username = null;
        this.userId = null;

        clearLoginState();
    }

    @Override
    public void init(Context context) {
        this.context = context.getApplicationContext();
        initSharedPreferences();

        // 从 SharedPreferences 恢复登录状态
        restoreLoginState();
    }

    /**
     * 初始化 SharedPreferences
     */
    private void initSharedPreferences() {
        if (context != null && sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        }
    }

    /**
     * 确保在使用前 SharedPreferences 已初始化
     */
    private void ensureSharedPreferencesInitialized() {
        if (sharedPreferences == null && context != null) {
            initSharedPreferences();
        }

        // 如果仍然为空，尝试使用 Application Context
        if (sharedPreferences == null) {
            try {
                Context appContext = getAppContext();
                if (appContext != null) {
                    sharedPreferences = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取 Application Context
     */
    private Context getAppContext() {
        try {
            // 通过反射获取 Application Context
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            return (Context) activityThreadClass.getMethod("getApplication").invoke(activityThread);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存登录状态到 SharedPreferences
     */
    private void saveLoginState() {
        ensureSharedPreferencesInitialized();

        if (sharedPreferences == null) {
            // 如果仍然无法初始化，记录错误
            android.util.Log.e("UserServiceImpl", "SharedPreferences is null, cannot save login state");
            return;
        }

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
        editor.putString(KEY_USERNAME, username);
        if (userId != null) {
            editor.putString(KEY_USER_ID, userId);
        }
        editor.apply();

        android.util.Log.d("UserServiceImpl", "Login state saved: " + isLoggedIn + ", username: " + username);
    }

    /**
     * 从 SharedPreferences 恢复登录状态
     */
    private void restoreLoginState() {
        ensureSharedPreferencesInitialized();

        if (sharedPreferences == null) {
            android.util.Log.e("UserServiceImpl", "SharedPreferences is null, cannot restore login state");
            return;
        }

        isLoggedIn = sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
        username = sharedPreferences.getString(KEY_USERNAME, null);
        userId = sharedPreferences.getString(KEY_USER_ID, null);

        android.util.Log.d("UserServiceImpl", "Login state restored: " + isLoggedIn + ", username: " + username);
    }

    /**
     * 清除登录状态
     */
    private void clearLoginState() {
        ensureSharedPreferencesInitialized();

        if (sharedPreferences == null) return;

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_IS_LOGGED_IN);
        editor.remove(KEY_USERNAME);
        editor.remove(KEY_USER_ID);
        editor.apply();

        android.util.Log.d("UserServiceImpl", "Login state cleared");
    }
}
